<template>
  <div id="map-container">
    <div class="btn-wrap">
      <el-button size="mini" @click="handleLayer('SL')">矢量底图</el-button>
      <el-button size="mini" @click="handleLayer('YX')">影像底图</el-button>
      <el-button size="mini" @click="handleLayer('DX')">地形晕渲</el-button>
      <el-button size="mini" @click="addArcgis()">{{ showArcgis ? '隐藏' : '显示' }}arcgis</el-button>
      <el-button size="mini" @click="addWMS()">{{ showWMS ? '隐藏' : '显示' }}WMS</el-button>
      <el-button size="mini" @click="addMarker">标注</el-button>
      <el-button size="mini" @click="addLines">添加轨迹线</el-button>
      <el-button size="mini" @click="handleAnimation">{{ animating ? '停止' : '开始' }}动画</el-button>
      <el-button size="mini" @click="loadshp()">加载shp</el-button>
      <el-button size="mini" @click="addTxtMarker()">加载解析的文件</el-button>
      <input type="file" @change="handleFileChange" />
    </div>
   
    <!-- <div v-if="fileContent">
      <h2>文件内容:</h2>
      <pre>{{ fileContent }}</pre>
    </div> -->
  </div>
</template>
<script>
const {
  Map,
  View,
  layer: { Tile: TileLayer, Vector: VectorLayer },
  proj: { get },
  extent: { getWidth, getTopLeft },
  source: { WMTS, TileArcGISRest, TileWMS, Vector: VectorSource },
  tilegrid,
  Feature,
  geom: { Point, LineString },
  style: { Icon, Style, Fill, Stroke, Circle: CircleStyle },
  render: { getVectorContext }
} = ol;
const { WMTS: WMTSTileGrid } = tilegrid;

export const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const resolutions = [];
for (let z = 2; z < 19; ++z) {
  resolutions[z] = size / Math.pow(2, z);
}
 // 定义坐标系
//  proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
//  proj4.defs("EPSG:4326", "+proj=longlat +datum=WGS84 +no_defs");
 // 注册坐标系
//  ol.proj.proj4.register(proj4);
let map;
export default {
  data () {
    return {
      showArcgis: false,
      showWMS: false,
      lon: 116.244399,
      lat: 30.920459,
      speedInput: 5,
      animating: false,
      distance: 0,
      lastTime: null,
      position: null,
      geoMarker: null,
      vectorLayer: null,
      route: null,
      fileContent: null, // 用于存储文件内容
      linePoints:[]
    };
  },
  mounted () {
    this.initMap();
    this.handleLayer("SL")// 加载矢量底图
  },
  methods: {
    
    handleFileChange(event) {
            const file = event.target.files[0];
            if (!file) {
                return;
            }

            const reader = new FileReader();
            reader.onload = (e) => {
                this.fileContent = e.target.result;
                //console.log(this.fileContent)
                const lines = this.fileContent.split('\n'); // 使用换行符分割内容
                lines.forEach(line => {
                  this.linePoints.push(line.split(','))
                  // this.linePoints.push(line.split(','))
                });
            };
            reader.readAsText(file); // 读取文件内容为文本
            console.log(this.linePoints)
        },
    // 初始化地图
    initMap () {
      map = new Map({
        target: "map-container",
        view: new View({
          center: [116.297, 40.108],
          projection: projection,
          zoom: 18,
          maxZoom: 19,
          minZoom: 1,
        }),
      });
    },
    // 底图加载
    handleLayer (layerType = "SL") {
      const TIANDI_KEY = "31499a6260cb9f29558750d04a934256";
      //我的天地图web端key:028f2ff40aff7482bb3973395489525f
      //我的天地图服务器端key:3f1f41bc45f2e7d1dbba2ce87289c3a1

      // 对应的值是固定的
      const layerTypeMap = {
        SL: ["vec", "cva"], // [矢量底图, 矢量注记]
        YX: ["img", "cia"], // [影像底图, 影像注记]
        DX: ["ter", "cta"], // [地形晕渲, 地形注记]
      };

      // c: 经纬度投影 w: 球面墨卡托投影
      const matrixSet = "c";
      const layers = map.getLayers().getArray();
      if (layers.length > 0) {
        layers.forEach((item) => {
          if (item.name === 'base') map.removeLayer(item);
        });
      }
      // 底图
      const tdtLayer = new TileLayer({
        source: new WMTS({
          url: `http://t{0-6}.tianditu.com/${layerTypeMap[layerType][0]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
          layer: layerTypeMap[layerType][0],
          matrixSet: matrixSet,
          style: "default",
          crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
          format: "tiles",
          wrapX: true,
          zIndex: 1,
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            //resolutions: res.slice(0, 18),
            resolutions: resolutions,
            matrixIds: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
               "15",
                "16",
                 "17",
                 "18",
            ],
          }),
        }),
        name: 'base'
      })
      map.addLayer(tdtLayer);

      // 标注
      const tdtZJLayer = new TileLayer({
        source: new WMTS({
          url: `http://t{0-6}.tianditu.com/${layerTypeMap[layerType][1]}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
          layer: layerTypeMap[layerType][1],
          matrixSet: matrixSet,
          style: "default",
          crossOrigin: "anonymous", // 解决跨域问题 如无该需求可不添加
          format: "tiles",
          wrapX: true,
          zIndex: 1,
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions: resolutions,
            matrixIds: [
              "0",
              "1",
              "2",
              "3",
              "4",
              "5",
              "6",
              "7",
              "8",
              "9",
              "10",
              "11",
              "12",
              "13",
              "14",
              "15",
                "16",
                 "17",
                 "18",
            ],
          }),
        }),
        name: 'base'
      })
      map.addLayer(tdtZJLayer);

    },
    // 添加arcgis图层
    addArcgis () {
      this.showArcgis = !this.showArcgis;
      if (!this.arcgisLayer) { // 如果是第一次加载 则初始化
        const arcgisSource = new TileArcGISRest({
          url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer',
          crossOrigin: 'anonymous',
        });
        this.arcgisLayer = new TileLayer({
          source: arcgisSource,
          zIndex: 2,
        });
        map.addLayer(this.arcgisLayer)
      } else { // 不是第一次加载，控制显隐即可
        this.arcgisLayer.setVisible(this.showArcgis);
      }
    },
    addWMS () {
      this.showWMS = !this.showWMS;
      if (!this.wmsLayer) {
        this.wmsLayer = new TileLayer({
          source: new TileWMS({
            url: 'https://server.mars3d.cn/geoserver/mars/wms',
            params: { 'LAYERS': 'mars:hf' },
            serverType: 'geoserver',
            transition: 0,
          }),
        })
        map.addLayer(this.wmsLayer)
      } else {
        this.wmsLayer.setVisible(this.showWMS);
        map.getView().fit(this.wmsLayer);
      }
    },
    addMarker () {
      const geometry = new Point([this.lon, this.lat])
      const iconFeature = new Feature({
        geometry,
        name: 'marker',
        population: 4000,
        rainfall: 500,
      });

      const iconStyle = new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: '/images/camera.png',
        }),
      });

      iconFeature.setStyle(iconStyle);

      const vectorSource = new VectorSource({
        features: [iconFeature],
      });

      const vectorLayer = new VectorLayer({
        source: vectorSource,
      });
      map.addLayer(vectorLayer)
      map.getView().fit(geometry);
    },
    addTxtMarker () {
      let iconFeatures=[]
      const iconStyle = new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: 'fraction',
          anchorYUnits: 'pixels',
          src: '/images/camera.png',
          width:10,
          height:10,
        }),
      });
      // let geometryzoomTo=new Point([this.linePoints[1][4],this.linePoints[1][3]])
      // let geometryzoomTo=new Point([this.linePoints[1][5],this.linePoints[1][7]])
      this.linePoints.forEach(element => {
        let geometry = new Point([element[5],element[6]])
        const iconFeature = new Feature({
          geometry,
          name: 'marker',
          size: 10,
        });
        iconFeature.setStyle(iconStyle);
        iconFeatures.push(iconFeature)
      });

      // // const geometry = new Point([this.lon, this.lat])
      // const iconFeature = new Feature({
      //   geometry,
      //   name: 'marker',
      //   population: 4000,
      //   rainfall: 500,
      // });

      

     

      const vectorSource = new VectorSource({
        features: iconFeatures,
      });

      const vectorLayer = new VectorLayer({
        source: vectorSource,
      });
      console.log("aaaaaaaaaaaa")
      console.log(vectorSource)
      map.addLayer(vectorLayer)
      // map.getView().fit(geometryzoomTo);
    },
    addLines () {
      const that = this;
      fetch('https://geo.datav.aliyun.com/areas_v3/bound/geojson?code=110114').then(function (response) {
        response.json().then( (result)=> {
          const polyline = result.features[0].geometry.coordinates[0][0];
          const route = new LineString(polyline)
          that.route = route;
          const routeFeature = new Feature({
            type: 'route',
            geometry: route
          })
          const startMarker = new Feature({
            type: 'icon',
            geometry: new Point(route.getFirstCoordinate()),
          });
          const endMarker = new Feature({
            type: 'icon',
            geometry: new Point(route.getLastCoordinate()),
          });
          that.position = startMarker.getGeometry().clone();
          that.geoMarker = new Feature({
            type: 'geoMarker',
            geometry: that.position,
          });
          const styles = {
            'route': new Style({
              stroke: new Stroke({
                width: 6,
                color: [237, 0, 0, 0.8],
              }),
            }),
            'icon': new Style({
              image: new Icon({
                anchor: [0.5, 1],
                src: '/images/camera.png',
              }),
            }),
            'geoMarker': new Style({
              image: new CircleStyle({
                radius: 7,
                fill: new Fill({ color: 'black' }),
                stroke: new Stroke({
                  color: 'white',
                  width: 2,
                }),
              }),
            }),
          };
          that.styles =  styles
          // 设置图层
          that.routeLayer = new VectorLayer({
            source: new VectorSource({
              features: [routeFeature, that.geoMarker, startMarker, endMarker]
            }),
            style: function (feature) {
              return styles[feature.get('type')];
            },
          })
          // 添加图层
          map.addLayer(that.routeLayer)
          map.getView().fit(route, { padding: [170, 50, 30, 150] });

        })
      })
    },
    handleAnimation () {
      this.animating = !this.animating
      if (this.animating) {
        this.startAnimation();
      } else {
        this.stopAnimation();
      }
    },
    startAnimation () {
      this.animating = true;
      this.lastTime = Date.now();
      this.routeLayer.on("postrender", this.moveFeature);
      this.geoMarker.setGeometry(null);
    },

    stopAnimation () {
      this.animating = false;
      this.geoMarker.setGeometry(this.position);
      this.routeLayer.un("postrender", this.moveFeature);
    },
    moveFeature (event) {
      const speed = 10;
      const time = event.frameState.time;
      const elapsedTime = time - this.lastTime;
      this.distance = (this.distance + (speed * elapsedTime) / 1e5) % 2;
      this.lastTime = time;

      //按比例获取坐标位置
      const currentCoordinate = this.route.getCoordinateAt(
        this.distance > 1 ? 2 - this.distance : this.distance
      );
      this.position.setCoordinates(currentCoordinate);
      const vectorContext = getVectorContext(event);
      vectorContext.setStyle(this.styles.geoMarker);
      vectorContext.drawGeometry(this.position);
      map.render();
    },
    loadshp(){
      // var vectorsource = new VectorSource();
      // var vectorLayer = new VectorLayer({
      //     source: vectorsource,
      //     name:"shplayer"
      // });
      // map.addLayer(vectorLayer);
      // console.log(map.getLayers())

      
      // shapefile.open('../data/bou2_4p.shp', '../data/bou2_4p.dbf', {encoding: 'utf-8'})
      //     .then(function(source) {source.read().then(function log(result) {
      //             if (result.done) return;
      //             var feature = new ol.format.GeoJSON().readFeature(result.value, {
      //                 dataProjection: 'EPSG:3857',
      //                 featureProjection: 'EPSG:3857'
      //             });
      //             console.log("内容")
      //             console.log(feature)
      //             vectorsource.addFeature(feature);
      //             console.log(vectorsource)
      //             return source.read().then(log);
      //         });
      //     })
      //     .catch(function(error) {
      //         console.error(error.stack);
      //     });
      var vectorLayer = new ol.layer.Vector({
         source: new ol.source.Vector()

      });

      // shapefile.open('../data/chinashp/bou2_4p.shp')
      shapefile.open('../data/lfm20250110/空代码_点.shp')
        .then(source => source.read()
          .then(function log (result) {
            if (result.done) return;
             console.log(result.value)
              var feature = new ol.format.GeoJSON().readFeature(result.value);
              vectorLayer.getSource().addFeature(feature);
              return source.read().then(log);
             })).catch(error => console.error(error.stack));

       map.addLayer(vectorLayer);
      },
  },
};

</script>
<style scoped>
#map-container {
  width: 100vw;
  height: 100vh;
}

.btn-wrap {
  position: absolute;
  top: 20px;
  left: 40px;
  z-index: 2;
}
</style>
